package pl.edu.agh.sius.controller;

import javax.faces.application.FacesMessage;

import pl.edu.agh.sius.controller.FirstChoiceBB.Concern;
import pl.edu.agh.sius.model.EstateSplitRequestBB;
import pl.edu.agh.sius.model.InputFileData;
import pl.edu.agh.sius.utils.FacesHelper;
import pl.edu.agh.sius.utils.MailBuilder;
import pl.edu.agh.sius.utils.MailClient;

public class Concern1Controller extends ConcernController {

	private EstateSplitRequestBB bb = new EstateSplitRequestBB();

	public Concern1Controller() {
		super();
		concernTitle = FirstChoiceBB.concernTitles.get(Concern.ESTATE_SPLIT);
		stepTitles = new String[] { "Dane osobowe", "Załączniki",
				"Zgoda na przetwarzanie", "Zatwierdzenie wprowadzonych danych" };
		stepsNo = stepTitles.length;
	}

	/* miejsce na dodatkową walidacje */
	public String next() {
		if (step == 1 && !bb.areAttachementsValid(inputFileController)) {
			FacesHelper.addMessage("Niekompletny zbiór dokumentów.", null);
			return null;
		}
		if (step == 2 && !bb.isAgreement()) {
			FacesHelper.addMessage("Kontynuacja procedury wymaga zgody.", null);
			return null;
		}
		return super.next();
	}

	@Override
	public String submit() {
		try {

			arrangeAttachments();
			MailClient.sendMail(MailBuilder.buildMail(bb, inputFileController),
					Concern.ESTATE_SPLIT);
			FacesHelper.addMessage("Podanie zostało prawidłowo wysłane.",
					FacesMessage.SEVERITY_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			FacesHelper.addMessage("Podanie nie zostało wysłane. Przyczyna: "
					+ e.getMessage(), FacesMessage.SEVERITY_INFO);
		} finally {
			popupController.setPopup(true);
		}
		return "restart";
	}

	private void arrangeAttachments() {
		for (InputFileData ifd : inputFileController.getFileList()) {
			if (ifd.getFileFormalName().equals(EstateSplitRequestBB.CADASTRE)) {
				bb.setCadastreFile(ifd.getFileInfo().getFile());
				bb.setCadastreDocURL(ifd.getDownloadURL());
			}
			if (ifd.getFileFormalName().equals(
					EstateSplitRequestBB.ESTATE_SPLIT_PETITION)) {
				bb.setEstateSplitPetitionFile(ifd.getFileInfo().getFile());
				bb.setEstateSplitPetitionDocURL(ifd.getDownloadURL());
			}
			if (ifd.getFileFormalName().equals(
					EstateSplitRequestBB.LOCAL_SPATIAL_PLAN)) {
				bb.setLocalSpatialPlanFile(ifd.getFileInfo().getFile());
				bb.setLocalSpatialPlanDocURL(ifd.getDownloadURL());
			}
			if (ifd.getFileFormalName().equals(
					EstateSplitRequestBB.PROPERTY_OWNERSHIP)) {
				bb.setPropertyOwnershipFile(ifd.getFileInfo().getFile());
				bb.setPropertyOwnershipDocURL(ifd.getDownloadURL());
			}
		}
	}

	public EstateSplitRequestBB getBb() {
		return bb;
	}

	public void setBb(EstateSplitRequestBB bb) {
		this.bb = bb;
	}

}
